﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Linq;
using System.Text;

namespace WooCoo.Data
{
    /// <summary>
    /// 一种通过计算器的方式来管理事务的类，继承类应该在获取事务引用时计数器+1.
    /// </summary>
    /// <typeparam name="C"></typeparam>
    /// <typeparam name="T"></typeparam>
    public abstract class TransactionManager : IDisposable
    {
        private static object _lock = new object();
        protected string ContextLabel { get; set; }

        public Type TransactionContextType { get; set; }

        #region 事务引用管理
        private int _refCount;
        public int RefCount
        {
            get { return _refCount; }
        }

        /// <summary>
        /// 在本次连接上,增加一次事务
        /// </summary>        
        protected virtual void AddRef()
        {
            _refCount += 1;
        }

        /// <summary>
        /// 
        /// </summary>
        protected virtual void DeRef()
        {
            lock (_lock)
            {
                _refCount -= 1;
                if (_refCount == 0)
                {
                    //if not need trans
                    TransactionDispose();
                    ApplicationContext.LocalContext.Remove(ContextLabel);
                }
            }

        }

        protected virtual void BeginTranaction()
        {
            this.AddRef();
        }
        protected abstract void TransactionDispose();

        #endregion

        #region 事务提交
        private bool _commit = false;
        /// <summary>
        /// 事务提交方法
        /// </summary>
        /// <returns></returns>
        protected abstract int CommitInternal();
        
        /// <summary>
        /// 事务提交，当引用数为1时，表示可提交事务。事务的提交将在最外层Using中
        /// </summary>
        public int Commit()
        {
            lock (_lock)
            {
                //_refCount -= 1;
                if (_refCount == 1)
                {
                    return this.CommitInternal();
                }
                return 0;
            }
        }
        #endregion

        /// <summary>
        /// 拼接上下文标识,以线程ID做为标识
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="label"></param>
        /// <returns></returns>
        private static string GetContextName(string database, string label)
        {
            return "__transaction:" + database + "-" + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString();
        }

        #region IDisposable 成员

        public void Dispose()
        {
            DeRef();
        }

        #endregion
    }
}
